package cn.tonyandmoney.voicenotes.alarm.ui

import android.content.Context
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Bundle
import android.os.PowerManager
import android.os.SystemClock
import android.os.Vibrator
import android.view.Gravity
import android.view.WindowManager
import cn.tonyandmoney.voicenotes.R
import com.zlzsy.app.base.ui.BaseActivity
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk25.coroutines.onClick


/**
 * 闹钟界面
 */
class AlarmActivity : BaseActivity(), AnkoLogger, MediaPlayer.OnCompletionListener {


    private var vibrator: Vibrator? = null
    private var mediaPlayer: MediaPlayer? = null
    private var ring = 0
    private var msg = "您有一个新闹钟..."


    override fun initView() {
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        val id = intent.getIntExtra("id", -1)
        ring = intent.getIntExtra("flag", 0)
        msg = intent.getStringExtra("msg")

        info("onReceive: msg->$msg  ring->$ring  id->$id")

        verticalLayout {
            textView {
                text = msg
                textSize = 25f
                padding = dip(20)
                onClick { cancel() }
            }.lparams(wrapContent, wrapContent)
            gravity = Gravity.CENTER
            lparams(matchParent, matchParent)
        }
    }

    override fun initData(savedInstanceState: Bundle?) {

        val mPowerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
        // 点亮亮屏
        val mWakeLock = mPowerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
                or PowerManager.SCREEN_DIM_WAKE_LOCK, "Alarm")
        mWakeLock.acquire(5000)

        val audioMa = getSystemService(Context.AUDIO_SERVICE) as (AudioManager)
        audioMa.setStreamVolume(AudioManager.STREAM_MUSIC,
                audioMa.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
                AudioManager.FLAG_SHOW_UI)

        when (ring) {
            0 -> vibrator()
            1 -> {
                mediaPlayer = MediaPlayer.create(this, R.raw.sound)
                mediaPlayer?.start()
            }
            2 -> {
                mediaPlayer = MediaPlayer()
                val path = intent.getStringExtra("voice")
                info("initData voice ->$path")
                try {
                    mediaPlayer!!.setDataSource(path)
                    mediaPlayer!!.prepare()
                    mediaPlayer?.start()
                } catch (e: Exception) {
                    vibrator()
                }
            }
        }
        mediaPlayer?.setOnCompletionListener(this)
    }

    /**
     * 播放完毕后重新开始播放
     */
    override fun onCompletion(mp: MediaPlayer?) {
        Observable.create<Int> {
            SystemClock.sleep(1000)
            it.onNext(0);it.onComplete()
        }.subscribeOn(Schedulers.io())
                .subscribe { mediaPlayer?.start() }
    }

    private fun vibrator() {
        vibrator = this.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        val patter = longArrayOf(1000, 1000, 2000, 50)
        vibrator?.vibrate(patter, 0)
    }

    private fun cancel() {
        vibrator?.cancel()
        mediaPlayer?.stop()
    }

    override fun onDestroy() {
        super.onDestroy()
        cancel()
    }
}